/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.molyfun.parents.im.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.model.styles.EaseMessageListItemStyle;
import com.molyfun.parents.im.ChatMessageList;
import com.molyfun.parents.im.MessageType;
import com.molyfun.parents.im.chatrow.BaseChatRow;
import com.molyfun.parents.im.chatrow.ChatRowAppraise;
import com.molyfun.parents.im.chatrow.ChatRowImage;
import com.molyfun.parents.im.chatrow.ChatRowProduct;
import com.molyfun.parents.im.chatrow.ChatRowSubject;
import com.molyfun.parents.im.chatrow.ChatRowText;
import com.molyfun.parents.im.chatrow.ChatRowVideo;
import com.molyfun.parents.im.chatrow.ChatRowVoice;
import com.molyfun.parents.im.model.ChatMessageEntity;
import com.molyfun.parents.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class MessageAdapter extends BaseAdapter  {

	private final static String TAG = "msg";
	private final static String TAGS = "MessageAdapter";

	private Context context;

	private static final int HANDLER_MESSAGE_REFRESH_LIST = 0;
	private static final int HANDLER_MESSAGE_SELECT_LAST = 1;
    private static final int HANDLER_MESSAGE_SEEK_TO = 2;

	private static final int MESSAGE_TYPE_RECV_TXT = 0;
	private static final int MESSAGE_TYPE_SENT_TXT = 1;
	private static final int MESSAGE_TYPE_SENT_IMAGE = 2;
	private static final int MESSAGE_TYPE_RECV_IMAGE = 3;
	private static final int MESSAGE_TYPE_SENT_VOICE = 4;
	private static final int MESSAGE_TYPE_RECV_VOICE = 5;
	private static final int MESSAGE_TYPE_SENT_VIDEO = 6;
	private static final int MESSAGE_TYPE_RECV_VIDEO = 7;
	private static final int MESSAGE_TYPE_RECV_PRODUCT = 8;
	private static final int MESSAGE_TYPE_RECV_EVALUATE = 9;

	List<ChatMessageEntity> messages = null;

    private ChatMessageList.MessageListItemListener itemClickListener;

    private boolean showUserNick;

    private ListView listView;
	private EaseMessageListItemStyle itemStyle;
	private BaseChatRow.MsgResendCallback msgResendCallback;

	public MessageAdapter(Context context, ListView listView, boolean showUserName, BaseChatRow.MsgResendCallback msgResendCallback) {
		this.context = context;
		this.listView = listView;
		this.showUserNick = showUserName;
		this.msgResendCallback = msgResendCallback;
	}

	Handler handler = new Handler() {
		private void refreshList() {
			// you should not call getAllMessages() in UI thread
			// otherwise there is problem when refreshing UI and there is new message arrive
//			java.util.List<EMMessage> var = conversation.getAllMessages();
//
//
//
////			messages = var.toArray(new EMMessage[var.size()]);
//            messages = convertDataList(var);
//			conversation.markAllMessagesAsRead();
			notifyDataSetChanged();
		}

		@Override
		public void handleMessage(android.os.Message message) {
			switch (message.what) {
			case HANDLER_MESSAGE_REFRESH_LIST:
				refreshList();
				break;
			case HANDLER_MESSAGE_SELECT_LAST:
                if (messages != null && messages.size() > 0) {
	                listView.setSelection(messages.size() - 1);
                }
                break;
            case HANDLER_MESSAGE_SEEK_TO:
	            int position = message.arg1;
	            listView.setSelection(position);
                break;
			default:
				break;
			}
		}
	};

	public void addData(ChatMessageEntity chatMessageEntity){
//		ChatMessageEntity chatMessageEntity = convertData(var);
		System.out.println("addData--->" + chatMessageEntity.toString());
		if(messages == null){
			messages = new ArrayList<>();
		}
		messages.add(chatMessageEntity);
		handler.sendMessage(handler.obtainMessage(HANDLER_MESSAGE_REFRESH_LIST));
//		notifyDataSetChanged();
	}

	public void clearData(){
		messages = new ArrayList<>();
		notifyDataSetChanged();
	}

	public void addLocallDataListHeader(java.util.List<ChatMessageEntity> var){
		if(messages == null){
			messages = new ArrayList<>();
		}
		messages.addAll(0, var);
//		notifyDataSetChanged();
		handler.sendMessage(handler.obtainMessage(HANDLER_MESSAGE_REFRESH_LIST));
	}

	public void addDataList(java.util.List<EMMessage> var){
		if(messages == null){
			messages = new ArrayList<>();
		}
		messages.addAll(convertDataList(var));
		handler.sendMessage(handler.obtainMessage(HANDLER_MESSAGE_REFRESH_LIST));
//		notifyDataSetChanged();
	}

	public List<ChatMessageEntity> convertDataList(java.util.List<EMMessage> var){
        List<ChatMessageEntity> list = new ArrayList<>(var.size());
        for(EMMessage message : var){
            list.add(convertData(message));
        }
        return list;
//        return list.toArray(new ChatMessageEntity[var.size()]);

    }


	public ChatMessageEntity convertData(EMMessage message) {

		if (message == null) {
			return null;
		}
		ChatMessageEntity cme = new ChatMessageEntity();
		cme.setUserid(message.getStringAttribute("userid", ""));
		cme.setId(message.getStringAttribute("id", ""));
		cme.setCustomplanid(message.getStringAttribute("customplanid", ""));
		cme.setUsername(message.getStringAttribute("username", ""));
		cme.setUsertype(message.getStringAttribute("usertype", ""));
		cme.setCreatedatetimeStr(message.getStringAttribute("createdatetimeStr", ""));
		cme.setCreatedatetime(message.getLongAttribute("createdatetime", 0));
		cme.setType(message.getStringAttribute("type", MessageType.TEXT));
		cme.setUrl(message.getStringAttribute("url", ""));
		cme.setBigurl(message.getStringAttribute("bigurl", ""));
		cme.setContent(StringUtils.decode(message.getStringAttribute("content", "")));
		cme.setCover(message.getStringAttribute("cover", ""));
		cme.setTimelen(message.getStringAttribute("timelen", ""));
		cme.setHeadimgurl(message.getStringAttribute("headimgurl", ""));
		cme.setExtendfield1(message.getStringAttribute("extendfield1", ""));
		cme.setExtendfield2(message.getStringAttribute("extendfield2", ""));
		cme.setExtendfield3(message.getStringAttribute("extendfield3", ""));
		cme.setExtendfield4(message.getStringAttribute("extendfield4", ""));
		cme.setExtendfield5(message.getStringAttribute("extendfield5", ""));
		cme.setExtendfield6(message.getStringAttribute("extendfield6", ""));

		return cme;

	}

	public void refresh() {
		if (handler.hasMessages(HANDLER_MESSAGE_REFRESH_LIST)) {
			return;
		}
		android.os.Message msg = handler.obtainMessage(HANDLER_MESSAGE_REFRESH_LIST);
		handler.sendMessage(msg);
	}

	/**
     * refresh and select the last
     */
    public void refreshSelectLast() {
        final int TIME_DELAY_REFRESH_SELECT_LAST = 100;
        handler.removeMessages(HANDLER_MESSAGE_REFRESH_LIST);
        handler.removeMessages(HANDLER_MESSAGE_SELECT_LAST);
        handler.sendEmptyMessageDelayed(HANDLER_MESSAGE_REFRESH_LIST, TIME_DELAY_REFRESH_SELECT_LAST);
        handler.sendEmptyMessageDelayed(HANDLER_MESSAGE_SELECT_LAST, TIME_DELAY_REFRESH_SELECT_LAST);
    }

    /**
     * refresh and seek to the position
     */
    public void refreshSeekTo(int position) {
	    handler.sendMessage(handler.obtainMessage(HANDLER_MESSAGE_REFRESH_LIST));
    }

	public ChatMessageEntity getItem(int position) {
		if (messages != null && position < messages.size()) {
			return messages.get(position);
		}
		return null;
	}

	public long getItemId(int position) {
		return position;
	}

	/**
     * get count of messages
     */
    public int getCount() {
        return messages == null ? 0 : messages.size();
    }

	/**
	 * get number of message type, here 14 = (EMMessage.Type) * 2
	 */
	public int getViewTypeCount() {
        return 14;
    }


	/**
	 * get type of item
	 */
	public int getItemViewType(int position) {
        ChatMessageEntity message = getItem(position);
		if (message == null) {
			return -1;
		}

		if (message.getType().equals( MessageType.TEXT)) {
			return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_TXT : MESSAGE_TYPE_SENT_TXT;
		}
		if (message.getType().equals(MessageType.IMAGE)) {
			return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_IMAGE : MESSAGE_TYPE_SENT_IMAGE;

		}
		if (message.getType().equals(MessageType.VOICE)) {
			return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VOICE : MESSAGE_TYPE_SENT_VOICE;
		}
		if (message.getType().equals(MessageType.VIDEO)) {
			return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VIDEO : MESSAGE_TYPE_SENT_VIDEO;
		}
		if (message.getType().equals(MessageType.PRODUCT)) {
			return MESSAGE_TYPE_RECV_PRODUCT;
		}
		if (message.getType().equals(MessageType.EVALUATE)) {
			return MESSAGE_TYPE_RECV_EVALUATE;
		}
		return -1;// invalid
	}

    protected BaseChatRow createChatRow(Context context, ChatMessageEntity message, int position) {
        BaseChatRow chatRow = null;

        System.out.println("createChatRow--->" + message.getType());

        if (message.getType().equals(MessageType.TEXT)) {
            chatRow = new ChatRowText(context, message, position, showUserNick, this);
        } else if (message.getType().equals(MessageType.IMAGE)) {
            chatRow = new ChatRowImage(context, message, position, showUserNick, this);
        } else if (message.getType().equals(MessageType.VOICE)) {
            chatRow = new ChatRowVoice(context, message, position, showUserNick, this);
        } else if (message.getType().equals( MessageType.VIDEO)) {
            chatRow = new ChatRowVideo(context, message, position, showUserNick, this);
        } else if (message.getType().equals(MessageType.PRODUCT)){
			chatRow = new ChatRowProduct(context, message, position, showUserNick, this);
		} else if (message.getType().equals(MessageType.EVALUATE)){
			chatRow = new ChatRowAppraise(context, message, position, this);
		} else if (message.getType().equals(MessageType.SUBJECT)){
			chatRow = new ChatRowSubject(context, message, position, showUserNick, this);
		}
		if(msgResendCallback != null && chatRow != null){
			chatRow.setMsgResendCallback(msgResendCallback);
		}else{
			chatRow = new ChatRowText(context, message, position, this);
		}

        return chatRow;
    }


	@SuppressLint("NewApi")
	public View getView(final int position, View convertView, ViewGroup parent) {
		ChatMessageEntity message = getItem(position);
//		if(convertView == null){
			convertView = createChatRow(context, message, position);
//		}

		((BaseChatRow)convertView).setUpView(message, position, itemClickListener, itemStyle);

		return convertView;
	}


	public void setItemStyle(EaseMessageListItemStyle itemStyle){
		this.itemStyle = itemStyle;
	}


    public void setItemClickListener(ChatMessageList.MessageListItemListener listener){
	    itemClickListener = listener;
	}


}
